//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    editable: true, //是否可编辑
    images: [], // 裁切完的图片
    enableCropper: false, // 是否启用裁切
    cutImages: null // 需要裁切的图片
  },
  onLoad: function () {

  },
  chooseImage () {
    var that = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#FAD143",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage1('album', 1)
          } else if (res.tapIndex == 1) {
            that.chooseWxImage1('camera', 1)
          }
        }
      }
    })
  },
  chooseWxImage1 (type, imglng) {
    var that = this;
    wx.chooseImage({
      count: imglng, // 最大图片数量
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: function (res) {
        that.setData({
          enableCropper: true,
          cutImages: res.tempFilePaths
        })
      }
    })
  },
  editImage1 () {
    this.setData({
      editable: !this.data.editable
    })
  },
  deleteImg (e) {
    console.log(e)
    const imgs = this.data.images
    Array.prototype.remove = function(i){
      const l = this.length;
      if(l==1){
        return []
      } 
      if (l > 1) {
        return [].concat(this.slice(0, i), this.slice(i + 1, l));
      }
    }
    this.setData({
      images: imgs.remove(e.currentTarget.dataset.index)
    })
  },
  success: function (evt) {
    console.log(evt)
    let images = this.data.images;
    let newimages = evt.detail;

    // 图片去重
    for (var i=0; i<images.length; i++) {
      for (var j=0; j<newimages.length; j++) {
        // 取图片链接后35位字符作为比较
        if (images[i].path.substring(images[i].path.length - 35, images[i].path.length) == newimages[j].path.substring(newimages[j].path.length - 35, newimages[j].path.length)) {
          newimages.splice(j, 1);
          break;
        }
      }
    }

    this.setData({
      enableCropper: false,
      cutImages: null,
      images: this.data.images.concat(newimages)
    });
  },
  failure: function (evt) {
    this.setData({
      cutImages: null,
      enableCropper: false
    });
  },
})
